#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import re
import markdown
import os

def txt2html(txtfile,htmlfile):
    '''
    将一个txt文件转换为一个html文件
    '''
    #读取txt
    a=open(txtfile,encoding="utf-8")
    b=a.read()
    # print(b)
    abc=markdown.markdown(b)
    a.close()
    #正则表达式分成一个列表
    input =re.findall(u'.*</[^>]+>',abc.replace("\n","</p><p>"))
    #改颜色
    for i in range(len(input)):
        if re.search(u'h1',input[i]):
            input[i]='<div  position: absolute style="color:#00FF00">'+input[i]+'</div>'
            print(input[i])
        elif re.search(u'h2',input[i]):
            input[i] = '<div style="color:#0000FF">' + input[i] + '</div>'
        elif re.search(u'<p>',input[i]):
            input[i] = '<div >' + input[i] + '</div>'
    #写入HTML文件
    h = open(htmlfile, 'w')
    for i in range(len(input)):
        h.write(input[i])
    h.close()

def read_dir_txt(txtpath,htmlpath):
    if os.path.isdir(txtpath):
        list_files_ = os.listdir(txtpath)
        for file_name in list_files_:
            txtfile_name_with_path = os.path.join(txtpath, file_name)
            htmlfile_name_with_path = os.path.join(htmlpath, file_name[:-4]+".html")
            print("start to strans file: " + txtfile_name_with_path)
            txt2html(txtfile_name_with_path, htmlfile_name_with_path)

if __name__ == "__main__":
    txtpath = "D:\\home\\RmadFile\\tran"
    htmlpath = "D:\\home\\RmadFile\\out"
    read_dir_txt (txtpath, htmlpath)
